import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:tx_live_plugin/tx_constant.dart';

///直播推流的控件
class TxLivePush extends StatelessWidget {

  final PushController? controller;
  final PushCallback? callback;

  const TxLivePush({Key? key, this.controller, this.callback}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    switch (defaultTargetPlatform) {
      case TargetPlatform.android:
        return AndroidView(
          viewType: platformFactory,
          creationParams: const {ViewType.key:ViewType.push},
          creationParamsCodec: const StandardMessageCodec(),
          onPlatformViewCreated: onPlatformViewCreated,
        );

      case TargetPlatform.iOS:
        return UiKitView(
          viewType: platformFactory,
          creationParams: const {ViewType.key:ViewType.push},
          creationParamsCodec: const StandardMessageCodec(),
          onPlatformViewCreated: onPlatformViewCreated,
        );

      default:
        return Center(
          child:
          Text("current platform ${Platform.operatingSystem} is not support"),
        );
    }

  }


  void onPlatformViewCreated(int id) {
    MethodChannel _channel = MethodChannel("${Channel.pushChannel}$id")
      ..setMethodCallHandler(_handler);
    controller?._setChannel = _channel;
  }

  ///处理原生发过来的消息
  Future _handler(MethodCall call) async {
    var method = call.method;
    var arg = call.arguments;
    switch (method) {
      case PushBack.error:
        if (arg is String) {
          callback?.error(arg);
          return;
        }
        _error(PushBack.error);
        break;
      case PushBack.toast:
        if (arg is String) {
          callback?.toast(arg);
          return;
        }
        _error(PushBack.toast);
        break;
      case PushBack.notifyPushStart:
        callback?.notifyPushStart();
        break;
      case PushBack.stopLivePush:
        bool cameraError = arg?[PushBackKey.cameraError] ?? false;
        bool needNoticeServer = arg?[PushBackKey.needNoticeServer] ?? false;
        callback?.stopLivePush(
          cameraError: cameraError,
          needNoticeServer: needNoticeServer,
        );
        break;
      case PushBack.toastSnackBar:
        if (arg is String) {
          callback?.toastSnackBar(arg);
          return;
        }
        _error(PushBack.toastSnackBar);
        break;
      case PushBack.videoProcessListener:
        callback?.videoProcessListener();
        break;
    }
  }

  _error(String name, {dynamic data}) {
    print("methodName $name is error, arguments $data");
    callback?.toastErrorInfo(name, data);
  }
}

///原生通知 flutter进行处理
mixin PushCallback {
  ///一些通知
  toast(String? message) {}

   ///推流失败通知
  error(String? message) {}

  ///接收到toast参数错误，无法正确弹出
  toastErrorInfo(String? method,dynamic data) {}

  ///推流时，网络很差，建议使用snack进行提示用户
  toastSnackBar(String? message) {}

  ///原生通知开始推流，需要请求服务端推流开始
  notifyPushStart() {}

  ///原生推流遇到 停止推送问题：是否是摄像头异常，是否需要通知服务端推流结束
  stopLivePush({bool? cameraError, bool? needNoticeServer}) {}

  ///视频开始推流监听，用于移除推送显示的提示语
  videoProcessListener() {}
}

///推流控制
class PushController extends ChangeNotifier {
  MethodChannel? _channel;

  set _setChannel(MethodChannel channel) => _channel = channel;

  ///通过channel通知原生处理数据
  _notifyChannel(String methodName, {dynamic data}) async {
    final c = _channel;
    if (c == null) {
      print(
          "tx_live_plugin PushController' channel is null，cannot use methodName $methodName");
      return -1;
    }
    return await c.invokeMethod(methodName, data);
  }

  ///开始推流
  startLivePush({String? url, int? serverTime, bool? isBitrateStandard}) {
    return _notifyChannel(PushMethod.startLivePush, data: {
      PushKey.url: url,
      PushKey.serverTime: serverTime,
      PushKey.isBitrateStandard: isBitrateStandard,
    });
  }

  ///结束推流
  stopLivePush() {
    return _notifyChannel(PushMethod.stopLivePush);
  }

  ///暂停
  onPause() {
    return _notifyChannel(PushMethod.onPause);
  }

  ///重新唤起
  onResume() {
    return _notifyChannel(PushMethod.onResume);
  }

  ///销毁
  onDestroy() {
    return _notifyChannel(PushMethod.onDestroy);
  }

  ///是否推流中
  isPushRecording() {
    return _notifyChannel(PushMethod.isPushRecording);
  }

  ///切换闪光灯
  turnOnFlashLight() {
    return _notifyChannel(PushMethod.turnOnFlashLight);
  }

  ///闪光灯是否开启
  isFlashLightOpen() {
    return _notifyChannel(PushMethod.isFlashLightOpen);
  }

  ///是否是前置摄像头
  isFontCamera() {
    return _notifyChannel(PushMethod.isFontCamera);
  }

  ///切换摄像头
  switchCamera() {
    return _notifyChannel(PushMethod.switchCamera);
  }

  @override
  void dispose() {
    super.dispose();
    print("----------------push page PushController dispose");
    onDestroy();
  }
}
